Java8 Stream介绍

直接上程序, 一些练习的例子全拿出来了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
/**
*filter使用,找到第一个,找不到返回null,
*/
@Test
public void streamTest() {
List<String> lists = Lists.newArrayList(null, null, "bb", "cc");
String str = lists.stream().filter(st -> "aa".equals(st)).findFirst().orElse(null);
System.out.println(str);
}

@Test
public void testOptional() {
//没有删除方法
List<String> names = Arrays.asList("Mal", "Wash", "Kaylee", "Inara",
"Zoë", "Jayne", "Simon", "River", "Shepherd Book", "CA");
Optional<String> first = names.stream().filter(name -> name.startsWith("C")).findFirst();
System.out.println(first);
System.out.println(first.orElse("None"));

System.out.println(first.orElse(getFormat(names)));

System.out.println(first.orElseGet(() ->
getFormat(names)));

System.out.println(first.orElseThrow(() -> new NullPointerException("异常")));


}

private String getFormat(List<String> names) {
System.out.println(names);
return String.format("No result found in %s",
names.stream().collect(Collectors.joining(", ")));
}

@Test
public void testPredicate() {
List<String> names = Lists.newArrayList("Mal", "Wash", "Kaylee", "Inara",
"Zoë", "Jayne", "Simon", "River", null, "Shepherd Book", "CA");
Predicate<String> predicate = s -> s != null;
predicate = predicate.and(s -> s.length() == 5);
System.out.println(getNamesOfLength(predicate, names));
System.out.println(names.removeIf(s -> s == null || s.length() == 5));
System.out.println(names);
}

private String getNamesOfLength(Predicate<String> predicate, List<String> names) {
return names.stream().filter(predicate).collect(Collectors.joining(", "));
}

@Test
public void testFunction() {
ArrayList<String> names = Lists.newArrayList("Mal", "Wash", "Kaylee", "Inara",
"Zoë", "Jayne", "Simon", "River", "Shepherd Book");
//匿名内部类
List<Integer> nameLengths2 = names.stream().map(new Function<String, Integer>() {
@Override
public Integer apply(String s) {
return s.length();
}

}).collect(toList());
//lambda表达式
List<Integer> nameLengths = names.stream().map(s -> s.length()).collect(toList());
//方法引用
List<Integer> nameLengths1 = names.stream().map(String::length).collect(toList());
System.out.println(nameLengths);

Map<String, Integer> map = new HashMap<>();
map.put("11", 1);
map.computeIfPresent("11", (k, v) -> v = v + 1);
System.out.println(map);
}

@Test
public void testStream() {
Stream.generate(Math::random).limit(10).forEach(System.out::println);
List<Integer> ints = IntStream.range(10, 15).boxed().collect(toList());
System.out.println(ints);
List<Integer> ints2 = IntStream.rangeClosed(10, 15).boxed().collect(toList());
List<Integer> ints3 = IntStream.rangeClosed(10, 15).mapToObj(Integer::valueOf).collect(toList());
System.out.println(ints2);
}

@Test
public void testCollect() {
List<Integer> ints = IntStream.of(3, 1, 4, 1, 5, 9)
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
System.out.println(ints);
int[] intArray = IntStream.of(3, 1, 4, 1, 5, 9).toArray();
System.out.println(Arrays.toString(intArray));
}

/**统计的api**/
@Test
public void testCount() {
String[] strings = "this is an array of strings".split(" ");
long count = Arrays.stream(strings).map(String::length).count();
System.out.println(count);
int totalLength = Arrays.stream(strings).mapToInt(String::length).sum();
System.out.println(totalLength);
OptionalDouble ave = Arrays.stream(strings).mapToInt(String::length).average();
System.out.println(ave.getAsDouble());
System.out.println(Double.NaN);
OptionalInt max = Arrays.stream(strings).mapToInt(String::length).max();
System.out.println(max.getAsInt());
OptionalInt min = Arrays.stream(strings).mapToInt(String::length).min();
System.out.println(min.getAsInt());
int sum = Arrays.stream(strings).mapToInt(String::length).reduce((x, y) -> x + y).orElse(0);
System.out.println(sum);
}
/**String字符串拼接*/
@Test
public void testReduceStrJoin1() {
String s = Stream.of("this", "is", "a", "list")
.collect(() -> new StringBuilder(),
(sb, str) -> sb.append(str),
(sb1, sb2) -> sb1.append(sb2))
.toString();
System.out.println(s);
}

/**其他类型的可以通过StringUtils进行拼接:
List<Long> teacherIds = Lists.newArrayList(12L,13L,18L);
String teacherIdsStr = StringUtils.join(teacherIds.iterator(), ",");
**/
@Test
public void testReduceStrJoin2() {
String s = Stream.of("this", "is", "a", "list")
.collect(StringBuilder::new,
StringBuilder::append,
StringBuilder::append)
.toString();
System.out.println(s);
}

@Test
public void testReduceStrJoin3() {
String s = Stream.of("this", "is", "a", "list")
.collect(Collectors.joining());
System.out.println(s);
}

@Test
public void testReducePrim() {
List<Book> books =
Lists.newArrayList(
new Book(1, "Java 1"),
new Book(1, "Java 2"),
new Book(3, "Java 3"),
new Book(4, "Java 4")
);
HashMap<Integer, Book> bookMap = books.stream()
.reduce(new HashMap<>(),
(map, book) -> {
map.put(book.getId(), book);
return map;
},
(map1, map2) -> {
map1.putAll(map2);
return map1;
});
bookMap.forEach((k, v) -> System.out.println(k + ": " + v));
}
/**
*List 变 map
*Collectors.toMap(Book::getId, b -> b) 第一个参数是key,第二个是value, 不允许有重复的
*下面允许将重复的保留第几个
*Collectors.toMap(Book::getId, Function.identity(), (k1, k2) -> k2)
*/
@Test
public void testReducetoMap() {
List<Book> books =
Lists.newArrayList(
new Book(1, "Java 1"),
new Book(1, "Java 2"),
new Book(3, "Java 3"),
new Book(4, "Java 4")
);
//不允许重复的
//Map<Integer, Book> bookMap = books.stream().collect(Collectors.toMap(Book::getId, b -> b));
//重复的归并到第二个
Map<Integer, Book> bookMap = books.stream().collect(Collectors.toMap(Book::getId, Function.identity(), (k1, k2) -> k2));
bookMap.forEach((k, v) -> System.out.println(k + ": " + v));
}
//reduce操作
@Test
public void testReduceSum() {
BigDecimal total = Stream.iterate(BigDecimal.ONE, n -> n.add(BigDecimal.ONE))
.limit(10)
.reduce(BigDecimal.ZERO, (acc, val) -> acc.add(val));
System.out.println("The total is " + total);
}

@Test
public void testReduceSort() {
List<String> strings = Lists.newArrayList(
"this", "is", "a", "list", "of", "strings");
List<String> sorted = strings.stream()
.sorted(Comparator.comparingInt(String::length))
.collect(toList());
System.out.println(sorted);
sorted.stream()
.reduce((prev, curr) -> {
assertTrue(prev.length() <= curr.length());
return curr;

});
}

@Test
public void sumDoublesDivisibleBy3() {
assertEquals(1554, sumDoublesDivisibleBy3(100, 120));

}

public int sumDoublesDivisibleBy3(int start, int end) {
return IntStream.rangeClosed(start, end)
.peek(n -> System.out.printf("original: %d%n", n))
.map(n -> n * 2)
.peek(n -> System.out.printf("doubled: %d%n", n))
.filter(n -> n % 3 == 0)
.peek(n -> System.out.printf("filtered: %d%n", n))
.sum();
}

@Test
public void testPalindrome() {
String str = "asisA";
System.out.println(isPalindrome1(str));
}

public boolean isPalindrome(String s) {
StringBuilder sb = new StringBuilder();
for (char c : s.toCharArray()) {
if (Character.isLetterOrDigit(c)) {
sb.append(c);
}
}
String forward = sb.toString().toLowerCase();
String backward = sb.reverse().toString().toLowerCase();
return forward.equals(backward);
}

public boolean isPalindrome1(String s) {
String forward = s.toLowerCase().codePoints()
.filter(Character::isLetterOrDigit)
.peek(n -> System.out.println(n))
.collect(StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append)
.toString();

String backward = new StringBuilder(forward).reverse().toString();
return forward.equals(backward);
}

/**
* count是一种特殊的归约,相当于
* long count = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5).mapToLong(e->1L).sum();
* return mapToLong(e -> 1L).sum();
*/
@Test
public void testItemsCount() {
long count = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5).count();
System.out.printf("There are %d elements in the stream%n", count);
}

/**
* Function.identity() 也就是 return t -> t;
*/
@Test
public void testD() {
List<Book> books =
Lists.newArrayList(
new Book(1, "Java 1"),
new Book(1, "Java 2"),
new Book(3, "Java 3"),
new Book(4, "Java 4")
);
Map<Integer, Book> bookMap = books.stream().collect(Collectors.toMap(b -> b.getId(), Function.identity(), (k1, k2) -> k2));
System.out.println(bookMap);
}

@Test
public void testPartitioning() {
List<String> strings = Lists.newArrayList(
"this", "is", "a", "list", "of", "strings");
Map<Boolean, Long> numberLengthMap = strings.stream()
.collect(Collectors.partitioningBy(
s -> s.length() % 2 == 0,
Collectors.counting()));
Map<Boolean, List<String>> stringsPartitionMap = strings.stream()
.collect(Collectors.partitioningBy(
s -> s.length() % 2 == 0));

numberLengthMap.forEach((k, v) -> System.out.printf("%5s: %d%n", k, v));
System.out.println(stringsPartitionMap);
}

/**
* 用户希望获取数值流中元素的数量、总和、最小值、最大值以及平均值。
*/
@Test
public void testSummaryStatistics() {
//DoubleStream.generate(Math::random)
List<Double> doubleList = Lists.newArrayList(1.0, 2.1, 3.4);
DoubleSummaryStatistics stats = doubleList.stream().mapToDouble(d -> d)
.summaryStatistics();

System.out.println(stats);
System.out.println("count: " + stats.getCount());
System.out.println("min : " + stats.getMin());
System.out.println("max : " + stats.getMax());
System.out.println("sum : " + stats.getSum());
System.out.println("ave : " + stats.getAverage());
}

@Test
public void testOptionalFindFirst() {
Optional<Integer> firstEvenGT10 = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5)
.peek(i -> System.out.println(i))
.filter(n -> n % 2 == 0)
.findFirst();
System.out.println(firstEvenGT10);
}

@Test
public void testHash() {
List<String> wordList = Arrays.asList(
"this", "is", "a", "stream", "of", "strings");
Set<String> words = new HashSet<>(wordList);
Set<String> words2 = new HashSet<>(words);
// 接下来,添加和删除足够多的元素来强制进行再散列操作
IntStream.rangeClosed(0, 50).forEachOrdered(i ->
words2.add(String.valueOf(i)));
words2.retainAll(wordList);
// 这些集合是相等的,但具有不同的元素排序
System.out.println(words.equals(words2));
System.out.println("Before: " + words);
System.out.println("After : " + words2);
}

@Test
public void testFindAny() {
Optional<Integer> any = Stream.of(3, 1, 4, 1, 5, 9, 2, 6, 5)
.unordered()
.parallel()
.map(this::delay)
.findAny();

System.out.println("Any: " + any);
}

public Integer delay(Integer n) {
try {
Thread.sleep((long) (Math.random() * 100));
} catch (InterruptedException ignored) {
}
return n;
}

public boolean isPrime(int num) {
int limit = (int) Math.sqrt(num) + 1;
return num == 2 || num > 1 && IntStream.range(2, limit).noneMatch(divisor -> num % divisor == 0);
}

@Test
public void testIsPrimeUsingAllMatch() throws Exception {
assertTrue(IntStream.of(2, 3, 5, 7, 11, 13, 17, 19)
.allMatch(i -> isPrime(i)));
}

@Test
public void testIsPrimeWithComposites() throws Exception {
assertFalse(Stream.of(4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20)
.anyMatch(i -> isPrime(i)));
}

@Test
public void emptyStreamsDanger() {
assertTrue(Stream.empty().allMatch(e -> false));
assertTrue(Stream.empty().noneMatch(e -> true));
assertFalse(Stream.empty().anyMatch(e -> true));
}

@Test
public void testFlatMap() {
Customer sheridan = new Customer("Sheridan");
Customer ivanova = new Customer("Ivanova");
Customer garibaldi = new Customer("Garibaldi");

sheridan.addOrder(new Order(1))
.addOrder(new Order(2))
.addOrder(new Order(3));
ivanova.addOrder(new Order(4))
.addOrder(new Order(5));

List<Customer> customers = Lists.newArrayList(sheridan, ivanova, garibaldi);
customers.stream().map(Customer::getName).forEach(System.out::println);
customers.stream()
.map(Customer::getOrders)
.forEach(System.out::println);
customers.stream()
.map(customer -> customer.getOrders().stream())
.forEach(System.out::println);
customers.stream()
.flatMap(customer -> customer.getOrders().stream())
.forEach(System.out::println);
}

@Test
public void testStreamConcat() {
Stream<String> first = Stream.of("a", "b", "c").parallel();
Stream<String> second = Stream.of("X", "Y", "Z");
Stream<String> third = Stream.of("alpha", "beta", "gamma");
Stream<String> fourth = Stream.empty();

List<String> strings = Stream.of(first, second, third, fourth)
.reduce(Stream.empty(), Stream::concat)
.collect(Collectors.toList());
System.out.println(strings);
}

@Test
public void flatMap() {
Stream<String> first = Stream.of("a", "b", "c").parallel();
Stream<String> second = Stream.of("X", "Y", "Z");
Stream<String> third = Stream.of("alpha", "beta", "gamma");
Stream<String> fourth = Stream.empty();

List<String> strings = Stream.of(first, second, third, fourth)
.flatMap(Function.identity())
.collect(Collectors.toList());
List<String> stringList = Arrays.asList("a", "b", "c",
"X", "Y", "Z", "alpha", "beta", "gamma");
assertEquals(stringList, strings);
}

@Test
public void flatMapParallel() {
Stream<String> first = Stream.of("a", "b", "c").parallel();
Stream<String> second = Stream.of("X", "Y", "Z");
Stream<String> third = Stream.of("alpha", "beta", "gamma");
Stream<String> fourth = Stream.empty();

Stream<String> total = Stream.of(first, second, third, fourth)
.flatMap(Function.identity());
assertFalse(total.isParallel());

total = total.parallel();
assertTrue(total.isParallel());
}

@Test
public void testFilter() {
List<Book> books =
Lists.newArrayList(
new Book(1, "Java 1"),
new Book(1, null),
new Book(3, null),
new Book(4, "Java 4")
);
List<Book> booksFilter = books.stream().filter(t -> t.getId() != 1 && t.getTitle() != null).collect(Collectors.toList());
System.out.println(booksFilter);
}

@Test
public void testToSet() {
List<String> actors =
Stream.of("Hank Azaria", "Janeane Garofalo", "William H. Macy",
"Paul Reubens", "Ben Stiller", "Kel Mitchell", "Wes Studi")
.collect(Collectors.toCollection(LinkedList::new));
System.out.println(actors);
}

@Test
public void testToArray() {
String[] actors =
Stream.of("Hank Azaria", "Janeane Garofalo", "William H. Macy",
"Paul Reubens", "Ben Stiller", "Kel Mitchell", "Wes Studi").toArray(String[]::new);
System.out.println(actors);
}

@Test
public void testMap() {
Set<Book> books = Sets.newHashSet(
new Book(1, "A Java 1"),
new Book(1, "C Java 2"),
new Book(3, "D Java 3"),
new Book(4, "B Java 4"));

Map<Integer, String> bookMap = books.stream()
.collect(Collectors.toMap(Book::getId, Book::getTitle, (k1, k2) -> k2));
bookMap.entrySet().stream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())).
forEach(entry ->
System.out.printf("%s name %s%n", entry.getKey(), entry.getValue()));
}

/**
* 分区, 满足predicate的, 不满足predicate的
*/
@Test
public void testPartition() {
List<String> strings = Arrays.asList("this", "is", "a", "long", "list", "of",
"strings", "to", "use", "as", "a", "demo");

Map<Boolean, List<String>> lengthMap = strings.stream()
.collect(Collectors.partitioningBy(s -> s.length() % 2 == 0));

lengthMap.forEach((key, value) -> System.out.printf("%5s: %s%n", key, value));
}

/**
* 下游收集器
*/
@Test
public void testPartitionDownStream() {
List<String> strings = Arrays.asList("this", "is", "a", "long", "list", "of",
"strings", "to", "use", "as", "a", "demo");
Map<Boolean, Long> lengthNum = strings.stream()
.collect(Collectors.partitioningBy(s -> s.length() % 2 == 0, Collectors.counting()));
lengthNum.forEach((key, value) -> System.out.printf("%5s: %s%n", key, value));
}

@Test
public void testGrouping() {
List<String> strings = Arrays.asList("this", "is", "a", "long", "list", "of",
"strings", "to", "use", "as", "a", "demo");
Map<Integer, List<String>> lengthMap = strings.stream()
.collect(Collectors.groupingBy(String::length));
lengthMap.forEach((k, v) -> System.out.printf("%d: %s%n", k, v));
}

@Test
public void testMinMax() {
List<Employee> employees = Arrays.asList(
new Employee("Cersei", 250_000, "Lannister"),
new Employee("Jamie", 150_000, "Lannister"),
new Employee("Tyrion", 1_000, "Lannister"),
new Employee("Tywin", 1_000_000, "Lannister"),
new Employee("Jon Snow", 75_000, "Stark"),
new Employee("Robb", 120_000, "Stark"),
new Employee("Eddard", 125_000, "Stark"),
new Employee("Sansa", 0, "Stark"),
new Employee("Arya", 1_000, "Stark"));

Employee defaultEmployee =
new Employee("A man (or woman) has no name", 0, "Black and White");
Optional<Employee> optionalEmp = employees.stream()
.collect(Collectors.maxBy(Comparator.comparingInt(Employee::getSalary)));
System.out.println(optionalEmp);

Map<String, Optional<Employee>> groupByPartment =
employees.stream()
.collect(Collectors.groupingBy(
Employee::getDepartment,
Collectors.maxBy(Comparator.comparingInt(Employee::getSalary))));
System.out.println(groupByPartment);

}

@Test
public void testUnmodifyable() {
Map<String, Integer> map = Collections.unmodifiableMap(
new HashMap<String, Integer>() {{
put("have", 1);
put("the", 2);
put("high", 3);
put("ground", 4);
}});
}

}

class Employee {
private String name;
private Integer salary;
private String department;

// 其他方法

public Employee(String name, Integer salary, String department) {
this.name = name;
this.salary = salary;
this.department = department;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getSalary() {
return salary;
}

public void setSalary(Integer salary) {
this.salary = salary;
}

public String getDepartment() {
return department;
}

public void setDepartment(String department) {
this.department = department;
}

@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", salary=" + salary +
", department='" + department + '\'' +
'}';
}
}

class Book {
private Integer id;
private String title;
// 构造函数、getter和setter、toString、equals、hashCode…

public Book() {
}

public Book(Integer id, String title) {
this.id = id;
this.title = title;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

@Override
public String toString() {
return "Book{" +
"id=" + id +
", title='" + title + '\'' +
'}';
}
}

class Customer {
private String name;
private List<Order> orders = new ArrayList<>();

public Customer(String name) {
this.name = name;
}

public String getName() {
return name;
}

public List<Order> getOrders() {
return orders;
}

public Customer addOrder(Order order) {
orders.add(order);
return this;
}
}

class Order {
private int id;

public Order(int id) {
this.id = id;
}

public int getId() {
return id;
}

@Override
public String toString() {
return "Order{" +
"id=" + id +
'}';
}
}

package com.east.service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.junit.Test;

import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.*;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static junit.framework.TestCase.assertTrue;

/**
* @author zhaomingwei
* Created on 18/9/20.
*/
public class Lambda2Test {
@Test
public void testObjectNonNull() {
List<String> strings = Arrays.asList(
"this", null, "is", "a", null, "list", "of", "strings", null);
List<String> nonNullStrings = strings.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
System.out.println(nonNullStrings);
List<String> strings2 =
Arrays.asList("this", "is", "a", "list", "of", "strings");
assertTrue(Objects.deepEquals(strings2, nonNullStrings));
assertTrue(strings2.equals(nonNullStrings));
}

/**
* 从泛型中去掉空元素
*
* @param list
* @param <T>
*
* @return
*/
public <T> List<T> getNonNullElements(List<T> list) {
return list.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
}

@Test
public void testRequireNonNull() {
String s = null;
Objects.requireNonNull(s, () -> "不能为空");

}

private Map<Long, BigInteger> cache = new HashMap<>();

@Test
public void testMapNew() {
long time1 = System.nanoTime();
fib(70);
long time2 = System.nanoTime();
System.out.println(time2 - time1);
//fib2(70);
long time3 = System.nanoTime();
System.out.println(time3 - time2);
System.out.println(cache);
}

//computeIfAbsent如果键存在,返回对应的值,否则通过提供的函数计算新的值并保存
public BigInteger fib(long i) {
if (i == 0) {
return BigInteger.ZERO;
} else if (i == 1) {
return BigInteger.ONE;
}
return cache.computeIfAbsent(i, n -> fib(n - 2).add(fib(n - 1)));
}
//巨慢
public long fib2(long i) {
if (i == 0) {
return 0;
} else if (i == 1) {
return 1;
}
return fib2(i - 2) + fib2(i - 1);
}

@Test
public void testMapPresent() {
String sentence = "hello world hello kitty";
String[] strings = sentence.split(" ");
Map<String, Integer> wordCount = new HashMap<>();
Arrays.stream(strings).forEach(s -> wordCount.merge(s, 1, Integer::sum));
System.out.println(wordCount);
}

//冲突
public interface Company {
default String getName() {
return "Initech";
}

// 其他方法
}

public interface Employee {
String getFirst();

String getLast();

void convertCaffeineToCodeForMoney();

default String getName() {
return String.format("%s %s", getFirst(), getLast());
}
}

public class CompanyEmployee implements Company, Employee {
private String first;
private String last;

@Override
public void convertCaffeineToCodeForMoney() {
System.out.println("Coding...");
}

@Override
public String getFirst() {
return first;
}

@Override
public String getLast() {
return last;
}

@Override
public String getName() {
return String.format("%s %s", Employee.super.getName(), Company.super.getName());
}
}

//Function 接口定义的复合方法
@Test
public void testFunctionCompose() {
Function<Integer, Integer> add2 = x -> x + 2;
Function<Integer, Integer> mult3 = x -> x * 3;

Function<Integer, Integer> mult3add2 = add2.compose(mult3);
Function<Integer, Integer> add2mult3 = add2.andThen(mult3);

System.out.println("mult3add2(1): " + mult3add2.apply(1));
System.out.println("add2mult3(1): " + add2mult3.apply(1));
}

//Consumer 接口定义的复合方法
@Test
public void testConsumer() {
Logger log = Logger.getLogger("");
Consumer<String> printer = System.out::println;
Consumer<String> logger = log::info;
Consumer<String> printThenLog = printer.andThen(logger);
Stream.of("this", "is", "a", "stream", "of", "strings").forEach(printThenLog);
}

//Predicate 接口定义的复合方法
@Test
public void testPredicate() {
Predicate<String> p = s -> s != null;
Predicate<String> p2 = p.and(s -> s.length() > 0);
String s = "";
System.out.println(p2.test(s));
}

@Test
public void testOptional() {
Optional optional = Optional.ofNullable(null);
System.out.println(optional.orElseGet(() -> Integer.parseInt("10000")));
Optional<String> firstEven =
Stream.of("five", "even", "length", "string", "values")
.filter(s -> s.length() % 2 == 0)
.findFirst();
System.out.println(firstEven.orElse("null"));
}

@Test
public void testIO() {
try (Stream<String> lines = Files.lines(Paths.get("/usr/share/dict/web2"))) {
lines.filter(s -> s.length() > 20)
.sorted(Comparator.comparingInt(String::length).reversed())
.limit(10)
.forEach(w -> System.out.printf("%s (%d)%n", w, w.length()));
} catch (IOException e) {
e.printStackTrace();
}
}

@Test
public void testLettersNumIO() {
try (Stream<String> lines = Files.lines(Paths.get("/usr/share/dict/web2"))) {
lines.filter(s -> s.length() > 20)
.collect(Collectors.groupingBy(String::length, Collectors.counting()))
.forEach((len, num) -> System.out.println(len + ": " + num));
} catch (IOException e) {
e.printStackTrace();
}
}

@Test
public void testLettersNumOrder() {
try (Stream<String> lines = Files.lines(Paths.get("/usr/share/dict/web2"))) {
Map<Integer, Long> map = lines.filter(s -> s.length() > 20)
.collect(Collectors.groupingBy(String::length, Collectors.counting()));
map.entrySet().stream()
.sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))
.forEach(entry -> System.out.println(entry.getKey() + ": " + entry.getValue()));
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 文件系统的遍历
*/
@Test
public void testFileScan() {
try (Stream<Path> paths = Files.walk(Paths.get("src/main/java"))) {
paths.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}

@Test
public void testFileFind() {
try (Stream<Path> paths =
Files.find(Paths.get("src/main/java"), Integer.MAX_VALUE,
(path, attributes) ->
!attributes.isDirectory() && path.toString().contains("Lambda"))) {
paths.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}

@Test
public void testTimeNow() {
System.out.println("Instant.now(): " + Instant.now());
System.out.println("LocalDate.now(): " + LocalDate.now());
System.out.println("LocalTime.now(): " + LocalTime.now());
System.out.println("LocalDateTime.now(): " + LocalDateTime.now());
System.out.println("ZonedDateTime.now(): " + ZonedDateTime.now());
}

@Test
public void testTimeOf() {
System.out.println("First landing on the Moon:");
LocalDate moonLandingDate = LocalDate.of(1969, Month.JULY, 20);
LocalTime moonLandingTime = LocalTime.of(20, 18);
System.out.println("Date: " + moonLandingDate);
System.out.println("Time: " + moonLandingTime);

System.out.println("Neil Armstrong steps onto the surface: ");
LocalTime walkTime = LocalTime.of(20, 2, 56, 150_000_000);
LocalDateTime walk = LocalDateTime.of(moonLandingDate, walkTime);
System.out.println(walk);
}

@Test
public void convertDateToLocalDate() {
LocalDate localDate = convertFromUtilDateUsingInstant(new Date());
System.out.println(localDate);
}

public LocalDate convertFromUtilDateUsingInstant(Date date) {
return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
}

public LocalDateTime convertFromCalendarUsingGetters(Calendar cal) {
return LocalDateTime.of(cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH),
cal.get(Calendar.HOUR),
cal.get(Calendar.MINUTE),
cal.get(Calendar.SECOND));
}

@Test
public void testTiming() {
Instant start = Instant.now();
// 调用需要计时的方法
List<Integer> list = Lists.newArrayList();
for (int i = 0; i < 1024000; i++) {
list.add(Integer.valueOf(i));
if (i % 10 == 0) {
System.gc();
}
}
Instant end = Instant.now();
System.out.println(getTiming(start, end) + " seconds");
}
public static double getTiming(Instant start, Instant end) {
return Duration.between(start, end).toMillis() / 1000.0;
}

@Test
public void testList() {
Lists.newArrayList();
}


@Test
public void testTreeMap() {
//List<Integer> numbers = IntStream.range(-10, 10).boxed().collect(toList());
List<Integer> numbers = Lists.newArrayList(-10, -9, -8, -7, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, -5, 8, -6, 9);
System.out.println(numbers);
Map<Integer, Integer> map = Maps.newTreeMap(Comparator.<Integer>reverseOrder());
for (Integer i : numbers) {
map.put(i, i);
}
map.forEach((k, v)-> System.out.printf("%d, %d\n",k,v));

System.out.println();
}

@Test
public void testTreeMap2() {

//List<Integer> numbers = IntStream.of(3, 1, 4, 1, -1, -3, 9).boxed().collect(toList());
//List<Integer> numbers = new Random().ints().limit(10).boxed().collect(toList());
List<Integer> numbers = Lists.newArrayList(1033293453, 1688703861, -1397662954, 1358394462, 2144737669, 1683364491, 906680402, 2094148244, 898301002, 134828019);
System.out.println(numbers);
//TreeMap<Integer, Integer> map = Maps.newTreeMap(Comparator.<Integer>reverseOrder()); // 正确写法
//TreeMap<Integer, Integer> map = Maps.newTreeMap((o1, o2) -> o2 - o1);//错误,
TreeMap<Integer, Integer> map = Maps.newTreeMap((o1, o2) -> o2.compareTo(o1));
for (Integer i : numbers) {
map.put(i, i);
}
map.forEach((k, v)-> System.out.printf("%d, %d\n",k,v));

System.out.println();
}
@Test
public void testParallelStream() {
List<Long> list = LongStream.range(0, 10000).boxed().collect(Collectors.toList());
Stopwatch stopwatch = Stopwatch.createStarted();
logger.info("start");
Lists.partition(list, 2000).parallelStream().forEach(l -> {
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
long end1 = stopwatch.elapsed(TimeUnit.MILLISECONDS);
logger.info("end:{}", end1);
Lists.partition(list, 2000).stream().forEach(l -> {
try {
Thread.sleep(100L);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
long end2 = stopwatch.elapsed(TimeUnit.MILLISECONDS);
logger.info("end:{}", end2 - end1);
}
}
-------------感谢您的阅读祝您生活愉快!-------------
支持一杯咖啡
0%